/**
 * The MIT License
 *
 * Copyright (c) 2010 Benjamin Klum
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.helgoboss.background_operation_notification_ref_impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.helgoboss.background_operation_notification.BackgroundOperation;
import org.helgoboss.background_operation_notification.BackgroundOperationManager;
import org.helgoboss.background_operation_notification.BackgroundOperationObserver;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;

public class BackgroundOperationManagerRefImpl implements BackgroundOperationManager, BundleActivator {

	private static BundleContext bundleContext; 
	private ServiceTracker observerTracker;
	private ServiceTracker operationTracker;
	private Map<BackgroundOperation, ServiceRegistration> backgroundOperationServiceRegistrations = Collections
			.synchronizedMap(new HashMap<BackgroundOperation, ServiceRegistration>());
	
	public void startBackgroundOperation(BackgroundOperation op) {
		ServiceRegistration reg = bundleContext.registerService(BackgroundOperation.class.getName(), op, null);
		backgroundOperationServiceRegistrations.put(op, reg);
		for (Object obj: getNonEmptyServices(observerTracker)) {
			((BackgroundOperationObserver) obj).backgroundOperationStarted(op);
		}
	}
	
	public void stopBackgroundOperation(BackgroundOperation op) {
		ServiceRegistration reg = backgroundOperationServiceRegistrations.get(op);
		if (reg != null) {
			reg.unregister();
		}
		for (Object obj: getNonEmptyServices(observerTracker)) {
			((BackgroundOperationObserver) obj).backgroundOperationStopped(op);
		}
	}
    
    
    private Object[] getNonEmptyServices(ServiceTracker tracker) {
        if (tracker.getServices() == null) {
            return new Object[0];
        } else {
            return tracker.getServices();
        }
    }

	public void updateBackgroundOperation(BackgroundOperation op) {
		for (Object obj: getNonEmptyServices(observerTracker)) {
			((BackgroundOperationObserver) obj).backgroundOperationUpdated(op);
		}
	}

	public void start(BundleContext context) throws Exception {
		bundleContext = context;
		
		operationTracker = new ServiceTracker(context, BackgroundOperation.class.getName(), null); 
		operationTracker.open();
		
		observerTracker = new ServiceTracker(context, BackgroundOperationObserver.class.getName(), null) {
			@Override
			public Object addingService(ServiceReference reference) {
				BackgroundOperationObserver observer = (BackgroundOperationObserver) context.getService(reference);
				if (observer != null)
					for (Object obj: getNonEmptyServices(operationTracker)) {
						BackgroundOperation op = (BackgroundOperation) obj;
						observer.backgroundOperationStarted(op);
					}
				return observer;
			}
		};
		observerTracker.open();
		context.registerService(BackgroundOperationManager.class.getName(), this, null);
	}

	public void stop(BundleContext context) throws Exception {
		observerTracker.close();
		operationTracker.close();
		bundleContext = null;
	}
    
    
}